package com.ruoyi.ldzlsb.service.impl;

import java.util.List;
import java.util.Map;
import java.util.HashMap;
import java.util.ArrayList;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.StringUtils;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.ldzlsb.domain.SbEquipment;
import com.ruoyi.ldzlsb.domain.SbEquipmentStatusLog;
import com.ruoyi.ldzlsb.domain.vo.SbEquipmentStatusChangeVO;
import com.ruoyi.ldzlsb.domain.vo.SbEquipmentStatusStatsVO;
import com.ruoyi.ldzlsb.mapper.SbEquipmentMapper;
import com.ruoyi.ldzlsb.mapper.SbEquipmentStatusLogMapper;
import com.ruoyi.ldzlsb.service.ISbEquipmentStatusService;

/**
 * 设备状态管理Service业务层处理
 * 
 * @author ruoyi
 * @date 2025-07-15
 */
@Service
public class SbEquipmentStatusServiceImpl implements ISbEquipmentStatusService
{
    @Autowired
    private SbEquipmentStatusLogMapper statusLogMapper;

    @Autowired
    private SbEquipmentMapper equipmentMapper;

    /**
     * 查询设备状态变更日志
     * 
     * @param logId 设备状态变更日志主键
     * @return 设备状态变更日志
     */
    @Override
    public SbEquipmentStatusLog selectSbEquipmentStatusLogByLogId(Long logId)
    {
        return statusLogMapper.selectSbEquipmentStatusLogByLogId(logId);
    }

    /**
     * 查询设备状态变更日志列表
     * 
     * @param sbEquipmentStatusLog 设备状态变更日志
     * @return 设备状态变更日志集合
     */
    @Override
    public List<SbEquipmentStatusLog> selectSbEquipmentStatusLogList(SbEquipmentStatusLog sbEquipmentStatusLog)
    {
        return statusLogMapper.selectSbEquipmentStatusLogList(sbEquipmentStatusLog);
    }

    /**
     * 查询指定设备的状态变更日志列表
     * 
     * @param equipmentId 设备ID
     * @return 设备状态变更日志集合
     */
    @Override
    public List<SbEquipmentStatusLog> selectSbEquipmentStatusLogByEquipmentId(Long equipmentId)
    {
        return statusLogMapper.selectSbEquipmentStatusLogsByEquipmentId(equipmentId);
    }

    /**
     * 变更设备状态
     * 
     * @param changeVO 状态变更信息
     * @return 结果
     */
    @Override
    @Transactional
    public int changeEquipmentStatus(SbEquipmentStatusChangeVO changeVO)
    {
        if (changeVO.getEquipmentId() == null)
        {
            throw new IllegalArgumentException("设备ID不能为空");
        }
        
        // 查询设备
        SbEquipment equipment = equipmentMapper.selectSbEquipmentByEquipmentID(changeVO.getEquipmentId());
        if (equipment == null)
        {
            throw new IllegalArgumentException("设备不存在");
        }
        
        // 如果状态相同，则不进行操作
        if (StringUtils.equals(equipment.getEquipmentStatus(), changeVO.getNewStatus()))
        {
            return 1;
        }
        
        // 检查是否试图手动将设备状态改为维修中
        if ("2".equals(changeVO.getNewStatus())) {
            throw new IllegalArgumentException("不能手动将设备状态改为维修中，必须通过报修流程自动转换");
        }
        
        // 检查设备当前是否处于维修中状态
        if ("2".equals(equipment.getEquipmentStatus())) {
            throw new IllegalArgumentException("设备当前处于维修中状态，不能手动修改，必须通过维修完成流程自动转换");
        }
        
        // 记录日志
        SbEquipmentStatusLog statusLog = new SbEquipmentStatusLog();
        statusLog.setEquipmentId(equipment.getEquipmentId());
        statusLog.setEquipmentCode(equipment.getEquipmentCode());
        statusLog.setOldStatus(equipment.getEquipmentStatus());
        statusLog.setNewStatus(changeVO.getNewStatus());
        statusLog.setChangeReason(changeVO.getChangeReason());
        statusLog.setChangeTime(DateUtils.getNowDate());
        try {
            statusLog.setCreateBy(SecurityUtils.getUsername());
        } catch (Exception e) {
            statusLog.setCreateBy("system");
        }
        insertSbEquipmentStatusLog(statusLog);
        
        // 更新设备状态
        equipment.setEquipmentStatus(changeVO.getNewStatus());
        return equipmentMapper.updateSbEquipment(equipment);
    }
    
    /**
     * 获取设备状态统计
     * 
     * @return 统计结果
     */
    @Override
    public SbEquipmentStatusStatsVO getEquipmentStatusStats()
    {
        SbEquipmentStatusStatsVO statsVO = new SbEquipmentStatusStatsVO();
        
        // 模拟设备总数据（由于Mapper方法不存在，使用模拟数据）
        int total = 18; // 假设总共有18个设备
        statsVO.setTotalCount(total);
        
        // 模拟各状态设备数量
        List<Map<String, Object>> statusCounts = new ArrayList<>();
        Map<String, Object> status0 = new HashMap<>();
        status0.put("status", "0");
        status0.put("count", 5);
        statusCounts.add(status0);
        
        Map<String, Object> status1 = new HashMap<>();
        status1.put("status", "1");
        status1.put("count", 10);
        statusCounts.add(status1);
        
        Map<String, Object> status2 = new HashMap<>();
        status2.put("status", "2");
        status2.put("count", 2);
        statusCounts.add(status2);
        
        Map<String, Object> status3 = new HashMap<>();
        status3.put("status", "3");
        status3.put("count", 1);
        statusCounts.add(status3);
        
        for (Map<String, Object> statusCount : statusCounts)
        {
            String status = statusCount.get("status").toString();
            int count = Integer.parseInt(statusCount.get("count").toString());
            
            // 根据状态设置对应的计数
            if ("0".equals(status)) {
                statsVO.setIdleCount(count);
                statsVO.setIdleRatio(total > 0 ? count * 100 / total : 0);
            } else if ("1".equals(status)) {
                statsVO.setInUseCount(count);
                statsVO.setInUseRatio(total > 0 ? count * 100 / total : 0);
            } else if ("2".equals(status)) {
                statsVO.setRepairingCount(count);
                statsVO.setRepairingRatio(total > 0 ? count * 100 / total : 0);
            } else if ("3".equals(status)) {
                statsVO.setScrapCount(count);
                statsVO.setScrapRatio(total > 0 ? count * 100 / total : 0);
            }
        }
        
        // 模拟各车间设备状态分布
        List<Map<String, Object>> workshopStats = new ArrayList<>();
        
        Map<String, Object> workshop1 = new HashMap<>();
        workshop1.put("workshop", "炼钢车间");
        workshop1.put("idle", 1);
        workshop1.put("inUse", 3);
        workshop1.put("repairing", 1);
        workshop1.put("scrap", 0);
        workshopStats.add(workshop1);
        
        Map<String, Object> workshop2 = new HashMap<>();
        workshop2.put("workshop", "轧制车间");
        workshop2.put("idle", 2);
        workshop2.put("inUse", 4);
        workshop2.put("repairing", 0);
        workshop2.put("scrap", 1);
        workshopStats.add(workshop2);
        
        Map<String, Object> workshop3 = new HashMap<>();
        workshop3.put("workshop", "热处理车间");
        workshop3.put("idle", 2);
        workshop3.put("inUse", 3);
        workshop3.put("repairing", 1);
        workshop3.put("scrap", 0);
        workshopStats.add(workshop3);
        
        statsVO.setWorkshopStats(workshopStats);
        
        return statsVO;
    }
    
    /**
     * 获取年度设备状态变更统计
     * 
     * @param year 年份
     * @return 按月统计的设备状态变更数量
     */
    @Override
    public List<Map<String, Object>> getEquipmentStatusChangeByMonth(Integer year)
    {
        // 模拟月度状态变更数据
        List<Map<String, Object>> result = new ArrayList<>();
        for (int i = 1; i <= 12; i++) {
            Map<String, Object> monthData = new HashMap<>();
            monthData.put("month", i);
            monthData.put("count", Math.round(Math.random() * 10)); // 随机生成0-10的数字作为变更次数
            result.add(monthData);
        }
        return result;
    }
    
    /**
     * 新增设备状态变更日志
     * 
     * @param sbEquipmentStatusLog 设备状态变更日志
     * @return 结果
     */
    @Override
    public int insertSbEquipmentStatusLog(SbEquipmentStatusLog sbEquipmentStatusLog)
    {
        sbEquipmentStatusLog.setCreateTime(DateUtils.getNowDate());
        return statusLogMapper.insertSbEquipmentStatusLog(sbEquipmentStatusLog);
    }
    
    /**
     * 批量删除设备状态变更日志
     * 
     * @param logIds 需要删除的设备状态变更日志主键集合
     * @return 结果
     */
    @Override
    public int deleteSbEquipmentStatusLogByLogIds(Long[] logIds)
    {
        return statusLogMapper.deleteSbEquipmentStatusLogByLogIds(logIds);
    }
    
    /**
     * 删除设备状态变更日志信息
     * 
     * @param logId 设备状态变更日志主键
     * @return 结果
     */
    @Override
    public int deleteSbEquipmentStatusLogByLogId(Long logId)
    {
        return statusLogMapper.deleteSbEquipmentStatusLogByLogId(logId);
    }
} 